// logs.js
const util = require('../../utils/util.js')
import env from "../../utils/env";
const app = getApp()

let conversation_id = '';
// const msg1 = "你是一名面试官，我是一名应聘";
// const msg2 = "岗位的求职者。我的项目经历如下: ";
// const msg3 = "。请根据我上述的项目经历，用中文向我提出1个面试问题并进行回答，每个问题及其回答字数100字左右。";
Page({
  data: {
    num:1,//份数
    minusStatus:'disable',
    areaList: [],
    uPrice: 3.9,
    postage: 6,
    markup:2,
    total:0,
    remark: '',
    tPrice: '',
    photoId:'',
    type: '',
    logs: [],
    photoCount:'5',
    message: '',
    disabled: false,
    plain: false,
    downloaddisabled: false,
    downloadloading: false,
    loading: false,
    downloadUrl: '',
    playlistid: '',
    result: '',
    job: '',
    q: '',
    dialogShow: false,
    price: '请选择套餐',
    prodCode: '',
    supplier: '',
    indexstatus: -1,//默认显示
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},//
    areaList1: [
      '0.03元\n一次', '0.05元\n两次', '0.1元\n五次'],
    maxClickCount: 3, //定义允许最大的点击次数，超过次次数需要有分享或者其他逻辑处理
    list: [
      {
        icon: "",
        title: "地址",
        click: "goAddress"
      }
    ],
  },
  // 显示遮罩层
  showModal: function () {
    var that = this;
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 100,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    setTimeout(function () {
      that.fadeIn();//调用显示动画
    }, 100)
  },
  // 选择套餐
  getValueTap(e) {
    let dialogid = e.currentTarget.dataset.dialogid;
    this.setData({
      price: dialogid,//this.data.areaList[dialogid] 赋值给输入框
      indexstatus: dialogid, //更新
    })
  },
  // 隐藏遮罩层
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 100,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画   
    setTimeout(function () {
      that.setData({
        hideModal: true
      })
    }, 100)//先执行下滑动画，再隐藏模块

  },
  onLoad: function (options) {
    // var priceTemp = options.priceTemp;
    // let maxClickCount = wx.getStorageSync('maxClickCount')
    // if (!maxClickCount || maxClickCount == 0) {
    //   maxClickCount = 3
    // } else {
    //   this.data.maxClickCount = maxClickCount;
    // }
    // if (priceTemp == 3) {
    //   this.data.maxClickCount += 1;
    // } else if (priceTemp == 5) {
    //   this.data.maxClickCount += 2;
    // } else if (priceTemp == 10) {
    //   this.data.maxClickCount += 5;
    // }
    // this.setMaxClick(this.data.maxClickCount);
    var photo_count =this.data.photoCount ;
    var sum = this.data.uPrice+this.data.markup*(this.data.num-1)+this.data.postage;
    if(options.type ==0 || options.type ==1 || options.type ==2|| options.type ==15){
      photo_count=7;
    }else if(options.type ==6|| options.type == 8){
      photo_count=6;
    }else if(options.type ==10|| options.type ==11|| options.type ==13|| options.type ==14){
      photo_count=4;
    }else if(options.type ==7){
      photo_count=8;
    }else{
      photo_count=5;
    }
    this.setData({
      total:sum,
      photoCount:photo_count,
      type: options.type,
      job: options.situation,
      photoId:options.photoId,
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return {
          date: util.formatTime(new Date(log)),
          timeStamp: log
        }
      })
    })
  },
  //事件处理函数
  /*点击减号*/
  bindMinus: function() {
    var num = this.data.num;
    if (num>1) {
      num--;
    }
    var minusStatus = num>1 ? 'normal':'disable';
    var tempTotal;
    tempTotal=this.data.uPrice + this.data.markup*(num-1)+this.data.postage;
    this.setData({
      num:num,
      minusStatus:minusStatus,
      total:tempTotal
    })
  },
  /*点击加号*/
  bindPlus: function() {
    var num = this.data.num;
    num++;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    var tempTotal;
    tempTotal=this.data.uPrice + this.data.markup*(num-1)+this.data.postage;
    this.setData({
      num:num,
      minusStatus:minusStatus,
      total:tempTotal
    })
  },
  /*输入框事件*/
  bindManual: function(e) {
    var num = e.detail.value;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    var tempTotal;
    tempTotal=this.data.uPrice + this.data.markup*(num-1)+this.data.postage;
    this.setData({
      num:num,
      minusStatus:minusStatus,
      total:tempTotal
    })
  },
  setMaxClick(val) {
    let maxClickCountKey = 'maxClickCount'
    wx.setStorageSync(maxClickCountKey, val);
  },
  checkClickAuth(maxClickCount) {
    let clickCountKey = 'clickCount'
    //clickCount
    let clickCount = wx.getStorageSync(clickCountKey)
    if (!clickCount || clickCount == 0) {
      clickCount = 0
    }
    wx.setStorageSync(clickCountKey, clickCount)
    if (clickCount > maxClickCount) {
      return false
    }
    return true;
  },
  countClick() {//记录有效点击次数
    let clickCountKey = 'clickCount'
    //clickCount
    let clickCount = wx.getStorageSync(clickCountKey)
    if (!clickCount || clickCount == 0) {
      clickCount = 1
    } else {
      clickCount += 1
    }
    wx.setStorageSync(clickCountKey, clickCount)
  },
  tapDialogButton(e) {
    this.setData({
      dialogShow: false,
    })
    if (e.detail.index == 1) {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }
  },
  buttontap(e) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  onShareAppMessage(options) {
  },
  onShareTimeline(options) {
  },
  validate() {
    if (this.data.areaList.length == 0) {
      wx.showToast({
        title: '邮寄地址不能为空，请输入邮寄地址',
        icon: 'none',
        duration: 3000
      })
      return false;
    } else {
      return true;
    }
  },
  bindTextAreaBlur: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  /**生成商户订单 */
  generateOrder: function () {
    if (this.validate()) {
      if (!wx.getStorageSync('is_login')) {
        app.login();
      }else if(wx.getStorageSync('is_login')){
        wx.checkSession({
          success: (res) => {
            console.log("session valid");
          },
          fail: (res) => {
            console.log("session invalid");
            app.login();
          },
          complete: (res) => {},
        })
      }
      var third_session = wx.getStorageSync('third_session');
      var Authorization = wx.getStorageSync('access_token');
      var that = this;
      var priceTemp = that.data.total;
      var remark = that.data.remark;
      var postalAddress = that.data.areaList[0];
      var num = that.data.num;
      if(num == 0){
        wx.showToast({
          title: '份数不能为0，请重新输入',
        })
        return
      }
      var orderInfo = { "gName": '照片打印服务费', "product": '照片打印服务费', "orderType": '1', "photoId": that.data.photoId, "gPrice": priceTemp, "thirdSession": third_session, "amount": priceTemp, "remark": remark ,"productCount":num}
      console.log(orderInfo);      //统一支付
      console.log(Authorization);      //统一支付
      wx.request({
        url: env.api_host + '/identify/miniGenerateOrder',
        method: 'GET',
        header: {
          Authorization: Authorization,
        },
        data: {
          address: postalAddress,
          orderInfo: orderInfo,
        },
        success: function (res) {
          var resResult = res.data;
          if (resResult.code == 200) {
            console.log(resResult);
            var payInfo = resResult.data;
            //发起支付
            var param = {
              "timeStamp": payInfo.timeStamp,
              "package": payInfo.package,
              "paySign": payInfo.sign,
              "signType": "RSA",
              "nonceStr": payInfo.nonceStr,
              "priceTemp": priceTemp,
              "prepayId": payInfo.prepayId,
              "appId": payInfo.appId,
              "openId": payInfo.openId
            };
            that.pay(param);
          } else if (resResult.code == 500) {
            wx.showModal({
              title: '温馨提示',
              content: '服务器内部错误，请在【我的】->【联系我们】中反馈',
              complete: (res) => {
                if (res.cancel) {
                }
                if (res.confirm) {
                }
              }
            })
          } else {
            wx.showModal({
              title: '温馨提示',
              content: '服务器没有响应，请在【我的】->【联系我们】中反馈',
              complete: (res) => {
                if (res.cancel) {
                }
                if (res.confirm) {
                }
              }
            })
          }
        },
        complete: function (res) {
          console.log(res);
        }
      })
    }
  },

  /* 支付  */
  pay: function (param) {
    var prepayId = "prepay_id=" + param.prepayId;
    wx.requestPayment({
      openId: param.openId,
      appId: param.prepayId,
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: prepayId,
      signType: "RSA",
      paySign: param.paySign,
      success: function (res) {
        console.log("requestPayment success");
        wx.showToast({
          title: '支付成功',
          icon: 'fail',
          duration: 2000
        })
        wx.navigateTo({
          url: '/pages/order/index',
        })
      },
      fail: function (res) {
        console.log("requestPayment fail");
        wx.showToast({
          title: '支付失败',
          icon: 'fail',
          duration: 2000
        })
      },
      complete: function () {
        console.log("requestPayment complete");
      }
    })
  },
  //取消支付
  channelSelect: function () {
    wx.showToast({
      title: "你取消了订单"
    })
    wx.navigateBack({
      delta: 1, // 回退前 delta(默认为1) 页面
      success: function (res) {
        console.log("success");
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function () {
        console.log("fail");
      },
      complete: function () {
        console.log("complete");
      }
      // this.hidePay();
    })
  },
  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(600).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  //通过微信添加地址
  goAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        var provinceInfo = res.provinceName;
        var address = {
          "name": res.userName,
          "phone": res.telNumber,
          "province": res.provinceName,
          "city": res.cityName,
          "county": res.countyName,
          "detailInfo": res.detailInfo,
        };
        var tempPostage,tempTotal;
        //获取到的地址存到data里的areaList中
        if(provinceInfo != "江苏省" && provinceInfo != "浙江省" && provinceInfo != "上海市"){
          tempPostage=8;
        }else{
          tempPostage=6;
        }
        tempTotal=that.data.uPrice + that.data.markup*(that.data.num-1)+tempPostage;
        that.setData({
            postage:tempPostage,
            total:tempTotal
          })
        if (that.data.areaList == null) {
          that.setData({
            areaList: address
          });
        } else {
          that.data.areaList.pop();
          that.setData({
            areaList: that.data.areaList.concat(address)
          });
        }
      },
      fail: () => {
        this.openConfirm()   // 如果获取地址权限失败，弹出确认弹窗，让用户选择是否要打开设置，手动去开权限
      }
    })
  }
})
